import React, {FC, useState} from 'react';
import AsyncButton from '../components/AsyncButton';
import {FileSystem} from '../types';
import {StoreState} from '../store';
import {handlePathOpen} from '../fsOperations';

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

type PublishingProps = {
  repoData: FileSystem.Repo; 
  appData: StoreState['appData'];
}
const Publishing: FC<PublishingProps> = function CurrentApp({repoData, appData}) {
  const [s3BundleFilter, setS3BundleFilter] = useState('plugins');
  const appId = repoData.appId;
  const publishBundle = async (id: string|number) => {
    await fetch(`http://localhost:3100/plugin-server/home/${appId}/bundles/${id}`, {method: 'POST'});
    window.parent.postMessage({type: "requestAppData"}, "*");
  }

  const uploadWebBundles = async () => {
    await fetch(`http://localhost:3100/plugin-server/home/${appId}/uploadWebBundle`, {method: 'POST'});
    window.parent.postMessage({type: "requestAppData"}, "*");
  }

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

    window.parent.postMessage({type: "requestAppData"}, "*");
  }

    let publishedBundles = null;
    let s3Bundles = null;
    if (['inprogress', 'notstarted'].includes(appData.loadingInfo.status)) {
      publishedBundles = <div>Loading...</div>;
      s3Bundles = <div>Loading...</div>;
    } else if (appData.loadingInfo.status === 'error') {
      publishedBundles = <div>Error happened: {appData.loadingInfo.errorMessage}</div>
      s3Bundles = <div>Error happened: {appData.loadingInfo.errorMessage}</div>
    } else if (appData.loadingInfo.status === 'success') {
      let artefacts = appData.payload.manifest.codeArtefacts;
      const bundleTypes = ['plugins', 'navigators', 'ios-jsbundle', 'android-jsbundle'];
      const publishedIds: Array<number|'NULL'> = [];
      for (let bundleType of bundleTypes) {
        let artefact = artefacts.find(it => it.type === bundleType);
        if (artefact) {
          publishedIds.push(artefact.id);
        } else {
          publishedIds.push('NULL');
        }
      }
      publishedBundles = bundleTypes
        .map((bundleType, i) => {
          let activeClass = ""
          if (bundleType === s3BundleFilter) {
            activeClass = "border-orange-500";
          }

          return (
            <div key={bundleType} 
              className={`flex flex-col flex-1 border border-1 m-1 rounded justify-between ${activeClass} cursor-pointer`}
              onClick={() => setS3BundleFilter(bundleType)}
            >
              <div className="w-full flex justify-center text-center" style={{fontSize: 8}}>
                {bundleType}
              </div>
              <div className="w-full flex justify-center">{publishedIds[i]}</div>
            </div>
          );
      });
      publishedBundles = (<div className="flex flex-row">
        {publishedBundles}
      </div>)

      s3Bundles = appData.payload.bundles.filter(it => it.type === s3BundleFilter).map((it, i) => {
        return (
          <div key={i} className="flex flex-row justify-between w-full items-center px-2">
            <span>{it.id}</span>
            <AsyncButton label="Publish" onClick={() => publishBundle(it.id)}/>
          </div>
        );
      })
    }

  const renderLocalBundles = (bundles: FileSystem.LocalMobileBundle[], bundleType: 'ios'|'android', label: string) => {
    let rows = [<div className="p-2">no bundles yet</div>];
    if (bundles.length > 0) {
      rows = bundles.map(bundle => {
        return (<div key={bundle.fullPath} className="flex flex-row items-center justify-between px-2">
          <span>{formatter.format(bundle.timestamp)}</span>
          <AsyncButton label="Upload" onClick={() => uploadMobileBundle(bundle.timestamp, bundleType)}/>
        </div>);
      })
    }

    let finderButton = null;
    if (bundles.length > 0) {
      finderButton = (<button 
          className="w-5"
          onClick={() => handlePathOpen(repoData.fullPath + `/remoteCode/generated/bundles/${bundleType}`, 'finder')}
        >
          <img 
            alt="open in finder"
            src={require('../assets/finder.png')}
            className="w-full"
          />
        </button>
      );
    }

    return (<>
      <div className="flex flex-row items-center justify-between w-full pr-1">
        {label}
        {finderButton}
      </div>
      <div className="max-h-24 overflow-y-auto border text-xs mb-2">
        {rows}
      </div>
    </>);
  };

  return (
    <div className="border p-1 rounded">
      <div>Published</div>
      {publishedBundles}
      <div className="max-h-24 overflow-y-auto border text-xs mb-2">
        {s3Bundles}
      </div>

      {renderLocalBundles(repoData.codePushBundles.ios, 'ios', 'Local ios-jsbundles')}
      {renderLocalBundles(repoData.codePushBundles.android, 'android', 'Local android-jsbundles')}
      <div className="flex flex-row items-center justify-between w-full pr-1">
        Local web bundles
      </div>
      <div className="max-h-24 overflow-y-auto text-xs mb-2">
        <div className="max-h-24 overflow-y-auto border text-xs mb-2 p-2">
          <AsyncButton label="Upload Current WebBundles" onClick={uploadWebBundles}/>
        </div>
      </div>
    </div>
  );
}

export default Publishing;
