import React, {FC, useEffect, useContext} from 'react';
import { Outlet } from 'react-router-dom';
import Button from '../components/Button';
import RepoCloneButton from '../components/RepoCloneButton';
import {FileSystem} from '../types';
import {StoreContext, StoreDispatchContext, fetchWorkspaceData} from '../store';
import {handlePathOpen} from '../fsOperations';

export const WorkspaceListing: FC = function() {
  const dispatch = useContext(StoreDispatchContext);
  const store = useContext(StoreContext);
  useEffect(() => {
    fetchWorkspaceData(dispatch, true, true);
  }, [dispatch]);

  const toggleApp = async(repo: FileSystem.WorkspaceData['repos'][0], workspaceId: number) => {
    if (repo.isOpen) {
      await fetch(
        `http://localhost:3100/plugin-server/cli/workspaces/${workspaceId.toFixed(0)}/closeApp`, 
        {
          method: 'DELETE',
          body: JSON.stringify(repo),
          headers: {
            'Content-Type': 'application/json'
          }
        }
      );
    } else {
      await fetch(
        `http://localhost:3100/plugin-server/cli/workspaces/${workspaceId}/openApp/${repo.appId}`,
        {
          method: 'POST'
        }
      );
    }
    fetchWorkspaceData(dispatch, false, false);
  };

  let workspaces = null;
  if (store && store.workspaceData.loadingInfo.status === 'success') {
    workspaces = store.workspaceData.payload.map(workspace => {
      const repos = workspace.repos.map(repo => {
      return (
        <div className="border border-solid border-green-500 rounded p-1">
          <div className="self-center text-xs p-1">{repo.name}</div>
          <div className="self-center p-1" style={{fontSize: 10}}>{repo.apptileServer} </div>
          {/*<span className="justify-self-end align-self-center p-1"> location: </span> 
          <span className="self-center text-xs p-1">
            <button onClick={() => handlePathOpen(repo.fullPath, 'code')}>Open</button>
            <span>{repo.fullPath}</span>
          </span>

          <span className="justify-self-end align-self-center p-1"> gitRepo: </span> 
          <span className="self-center text-xs p-1">{repo.gitRepo} </span>

          <span className="justify-self-end align-self-center p-1"> appId: </span> 
          <span className="self-center text-xs p-1">{repo.appId} </span>

          <span className="justify-self-end align-self-center p-1"> apptileServer: </span> 
          <span className="self-center text-xs p-1">{repo.apptileServer} </span>

          <span className="justify-self-end align-self-center p-1"> configServer: </span> 
          <span className="self-center text-xs p-1">{repo.appconfigServer} </span>*/}
          <Button
            label={repo.isOpen ? "Close" : "Open"}
            onClick={() => toggleApp(repo, workspace.id)}
          />
        </div>
      );
    })
    return (<div className="flex flex-col items-start border border-solid p-1">
      <div className="flex flex-row gap-1 w-full">
        <button onClick={() => handlePathOpen(workspace.location, 'code')}>
          <img 
            alt="open in vscode"
            src={require('../assets/code.png')}
            className="w-10"
          />
        </button>
        <button onClick={() => handlePathOpen(workspace.location, 'finder')}>
          <img 
            alt="open in finder"
            src={require('../assets/finder.png')}
            className="w-10"
          />
        </button>
        <div className="flex flex-row items-center justify-end w-full">
          <span style={{fontSize: 10}}>{workspace.sdkHash}</span>
          <img
            alt="git repo status"
            src={require('../assets/github.png')}
            className="w-8"
          />
        </div>
      </div>
      <div className="flex flex-wrap">
        {repos}
      </div>
      <RepoCloneButton workspaceId={workspace.id}/>
    </div>);
    });
    
  } else if (store && store.workspaceData.loadingInfo.status === 'error') {
    workspaces = (<div>
      {store.workspaceData.loadingInfo.errorMessage}
      <br/>
      {store.workspaceData.loadingInfo.error.stack}
    </div>);
  } else if (store && store.workspaceData.loadingInfo.status === 'inprogress') {
    workspaces = <div>
      Loading...
    </div>
  } else {
    workspaces = <div>
      Uh oh!
    </div>
  }

  return (<>
    {workspaces}
    <Button label="new workspace" onClick={() => {}} />
  </>);
}

const Workspaces: FC = function() {
  return <Outlet />
}

export default Workspaces;
