import React, {FC, useContext} from 'react';
import {useMatch} from 'react-router-dom';
import Button from '../components/Button';
import {StoreContext} from '../store';

const formatter = Intl.DateTimeFormat('en-US', {
  dateStyle: 'long',
  timeStyle: 'short',
});

const OpenedApp: FC = function() {
  const match = useMatch('workspaces/:workspaceId/app/:appId');
  const appId = match?.params?.appId;
  const workspaceId = match?.params?.workspaceId;
  const store = useContext(StoreContext);
  let repoData = null;
  if (store && (store.workspaceData.loadingInfo.status === 'success') && workspaceId) {
    const numericWorkspaceId = parseInt(workspaceId)
    let workspace = store.workspaceData.payload.find(wrk => wrk.id === numericWorkspaceId);
    if (workspace) {
      repoData = workspace.repos.find(repo => {
        return repo.appId === appId
      })
    }
  }

  const startMetro = () => {
    fetch(`http://localhost:3100/plugin-server/home/${appId}/startMetro`, {method: 'POST'});
  };

  const killMetro = () => {
    fetch(`http://localhost:3100/plugin-server/home/killMetro`, {method: 'DELETE'});
  };

  const publishBundle = (id: string|number) => {
    fetch(`http://localhost:3100/plugin-server/home/${appId}/bundles/${id}`, {method: 'POST'})
  }

  const debugBuild = () => {
    fetch(`http://localhost:3100/plugin-server/home/${appId}/build/ios/debug`, {method: 'POST'});
  }

  const releaseBuild = () => {
    fetch(`http://localhost:3100/plugin-server/home/${appId}/build/ios/release`, {method: 'POST'});
  }

  const bundleIOS = () => {
    fetch(`http://localhost:3100/plugin-server/home/${appId}/bundleJsIOS`, {method: 'POST'})
  }

  const uploadMobileBundle = (bundleTimestamp: number, os: 'android'|'ios') => {
    fetch(`http://localhost:3100/plugin-server/home/${appId}/uploadMobileBundle/${bundleTimestamp}/${os}`, {method: 'POST'})
  }

  const runAndroid = () => {
    fetch(`http://localhost:3100/plugin-server/home/${appId}/runAndroid`, {method: 'POST'})
  }

  const buildAndroid = () => {
    fetch(`http://localhost:3100/plugin-server/home/${appId}/build/android/release`, {method: 'POST'})
  }

  const bundleAndroid = () => {
    fetch(`http://localhost:3100/plugin-server/home/${appId}/bundleJSAndroid`, {method: 'POST'})
  }

  let result = <div>Invalid appId or workspaceId</div>

  let renderedManifest = null;
  let s3Bundles = null;
  if (store) {
    switch (store.appData.loadingInfo.status) {
    case 'notstarted':
      renderedManifest = <div>Store fetch has not started yet! Wait</div>
      s3Bundles = <div>Store fetch has not started yet! Wait</div>
    break;
    case 'inprogress':
      renderedManifest = <div>Loading...</div>;
      s3Bundles = <div>Loading...</div>;
    break;
    case 'error':
      renderedManifest = (
        <div>Error ocurred: {store.appData.loadingInfo.errorMessage}</div>
      );
    break;
    case 'success':
      renderedManifest = store.appData.payload.manifest.codeArtefacts.map((it: any) => {
        return (
          <div key={it.cdnlink}>{it.type}:{it.id}</div>
        );
      });
      s3Bundles = (<div>
        <span>Bundles on s3</span>
        {store.appData.payload.bundles.map((it, i) => {
          return (
            <div key={i}>
              <span>{it.id}:{it.type}</span>
              <Button label="Publish" onClick={() => publishBundle(it.id)}/>
            </div>
          );
        })}
      </div>);
    break;
    default:
      renderedManifest = <div>Undefined state in store</div>;
    }

    if (!appId || !workspaceId) {
      result = <div>App home</div>;
    } else  if (store.workspaceData.loadingInfo.status === 'inprogress') {
      result = <div>Loading...</div>
    } else  if (store.workspaceData.loadingInfo.status === 'error') {
      result = <div>Error happend: {store.workspaceData.loadingInfo.errorMessage}</div>
    } else  if (store.workspaceData.loadingInfo.status === 'notstarted') {
      result = <div>Waiting for api call</div>
    } else  if (store.workspaceData.loadingInfo.status === 'success') {
      if (repoData) {
        result = (<div>
          <div>appid: {repoData.appId}</div>
          <div>approot: {repoData.fullPath}</div>
          <div className="flex flex-col gap-2">
            <Button label="Kill Metro" onClick={killMetro}/>
            <Button label="Start Metro" onClick={startMetro}/>
            <Button label="Bundle js(ios)" onClick={bundleIOS}/>
            <Button label="Debug Build(ios)" onClick={debugBuild}/>
            <Button label="Release Build(ios)" onClick={releaseBuild}/>
            <Button label="Bundle js(android)" onClick={bundleAndroid}/>
            <Button label="Debug Android" onClick={runAndroid}/>
            <Button label="Build Android" onClick={buildAndroid}/>
            <Button label="Distributable Build" onClick={() => {}}/>
            <Button label="Install App" onClick={() => {}}/>
          </div>
          {renderedManifest}
          {s3Bundles}
          <div>
            <span>ios Bundles</span>
            { 
              repoData.codePushBundles.ios.map(bundle => {
                return (<div key={bundle.fullPath}>
                  <span>{formatter.format(bundle.timestamp)}</span>
                  <Button label="Upload" onClick={() => uploadMobileBundle(bundle.timestamp, 'ios')}/>
                </div>);
              })
            }
          </div>
          <div>
            <span>android Bundles</span>
            { 
              repoData.codePushBundles.android.map(bundle => {
                return (<div key={bundle.fullPath}>
                  <span>{formatter.format(bundle.timestamp)}</span>
                  <Button label="Upload" onClick={() => uploadMobileBundle(bundle.timestamp, 'android')}/>
                </div>);
              })
            }
          </div>
        </div>);
      } else {
        result = (<div>No repo exists for this appId</div>)
      }
    } else {
      result = (<div>Invalid state for workspace app</div>)
    }
  } else {
    renderedManifest = <div>Store is not initialized</div>;
  }

  

  return result;
}

export default OpenedApp;
