import { redirect, useLoaderData } from 'react-router-dom';
import { IDoc, docReq } from '../request/doc';
import SharedQuill from '../components/collaboration-editors/quill';
import SharedKonva from '../components/collaboration-editors/konva';
import SharedSpreadSheets from '../components/collaboration-editors/spreadsheets';
import { konva_type, rich_text_type, spreadsheet_type } from '../ot-types';
import { notification } from 'antd';
import { normalizeError } from '../util/util';
import { IUser, userReq } from '../request/user';
import { Role } from '../enum';

export async function openLoader({ params }: any) {
    try {
        return await docReq.get(params.docId);
    } catch (error) {
        notification.error({
            message: "fetch doc error!",
            description: normalizeError(error)
        });
        return redirect('/all-files');
    }
}

export async function openShareLinkLoader({ params }: any) {
    try {
        const { docId } = await docReq.openShareLink(params.link);
        return await docReq.get(docId);
    } catch (error) {
        notification.error({
            message: "fetch doc error!",
            description: normalizeError(error)
        });
        return redirect('/all-files');
    }
}

export default function Open() {
    const d = useLoaderData() as IDoc;
    const user = userReq.currentUser() as IUser;
    console.log('open', d);

    return <Editor doc={d} user={user}></Editor>
}

function Editor(props: { doc: IDoc, user: IUser }) {
    const { doc, user } = props;
    const readonly = doc.role === Role.viewer;

    let editor;
    if (doc.type === konva_type.uri) {
        editor = <SharedKonva doc={doc} user={user} readonly={readonly} />
    } else if (doc.type === spreadsheet_type.uri) {
        editor = <SharedSpreadSheets doc={doc} user={user} readonly={readonly} />
    } else if (doc.type === rich_text_type.uri) {
        editor = <SharedQuill doc={doc} user={user} readonly={readonly} />
    } else {
        console.error('error');
    }

    return editor;
}