'use strict';

import React, {useState} from "react";
import * as ReactDOM from "react-dom/client";

function init() {
  const wrapper = document.querySelector('#screen');

  const root = ReactDOM.createRoot(wrapper);
  const html = (<SyncScreen/>);

  root.render(html);
}

function SyncScreen() {
  const [loading, setLoading] = useState(null);
  const [error, setError] = useState(null);

  return <>

    <section className="container py-5">
      <h1 style={{marginBottom: '2rem'}}>Oops... Block not in sync.</h1>
      {error && <p className="alert alert-danger">{error}</p>}

      {loading ?
        <>
          {loading === 'syncing' &&
            <p>Version upgrade in progress...</p>
          }
          <p>Please wait...</p>
        </>
        :
        <>
          <p>Your version of the block is not in sync with the cloud (not latest version).<br/>
            Would you like to update it?</p>
          <div className="options">
            <button className="btn btn-primary" style={{marginRight: '0.5rem'}} onClick={runSyncLogic}>Yes, Update to
              Latest
            </button>
            <button className="btn btn-secondary" onClick={ignoreVersionSync}>Ignore</button>
          </div>
        </>
      }
    </section>

  </>

  async function ignoreVersionSync() {
    // Add "ignore" query parameter to current URl and redirect.
    const url = new URL(window.location.href);
    url.searchParams.set('ignoreVersionSync', 'true');
    window.location = url.href;
  }

  async function runSyncLogic() {
    setLoading('syncing');

    let data = {};
    try {
      const response = await fetch('/sync', {
        method: 'POST',
        body: JSON.stringify({block: getQueryParams().block}),
        headers: {
          'Content-Type': 'application/json'
        }
      });

      data = await response.json();
    } catch (err) {
      setError('Error: ' + err.message);
      setLoading(false);
      return;
    }

    if (data.status !== 200) {
      setError(data.message);
      setLoading(false);
      return;
    }

    setTimeout(() => window.location.reload(), 1000);
  }

  // TODO: This function is used in multiple places (repeated code).
  //  Move to a common place.
  function getQueryParams() {
    const urlParams = new URLSearchParams(window.location.search);
    const params = {};

    for (const [key, value] of urlParams) {
      params[key] = value;
    }

    return params;
  }


}

init();

