import { AxiosInstance, AxiosRequestConfig } from "axios";
import { CatchError } from "./common";
import { accountClient, userClient } from "./axios";
import { BirthDateEditModel, DeleteSessionModel, LanguageEditModel, SessionModel, User, UserInformationEditModel } from "./models/AccountTypes";
import { MediaInfo, MediaInfoType } from "./models/Types";

export default async function GetUser(accessToken : string | null | undefined, client?: AxiosInstance | null) : Promise<User | null>{
    const config = accessToken != null
        ? { headers: {"Authorization" : `Bearer ${accessToken}`} } as AxiosRequestConfig
        : undefined;
    client ??= userClient;
    const getUserResponse = await client.get<User | null>('', config);
    return getUserResponse?.data;
}

export async function GetAvatar(accessToken : string | null) : Promise<MediaInfo | null>{
    // if (accessToken == null){
    // 	return Promise.reject("No user");
    // }
    // else{
    // 	console.log(`getAvatar accessToken: ${accessToken}`);
    // 	const config = {
    // 		url: 'avatar',
    // 		method: 'GET',
    // 		responseType: 'blob',
    // 		headers: { 'Authorization': `Bearer ${accessToken}` }
    // 	} as AxiosRequestConfig;
    // 	const response = await userClient.request<Blob | null>(config);
    // 	if (response.data == null) {
    // 		return Promise.reject();
    // 	}
    // 	else {
    // 		return new Promise((resolve, reject) => {
    // 			const reader = new FileReader();
    // 			reader.onload = () => resolve(reader.result as string | null);
    // 			reader.onerror = reject;
    // 			reader.readAsDataURL(response.data!);
    // 		});
    // 	}
    // 	// .catch(() => setAvatarString(null));
    // 	// .catch(() => {return Promise.reject();});
    // }

    // console.log(`getAvatar accessToken: ${accessToken}`);
    const config = {
        url: 'avatar',
        method: 'GET',
        responseType: 'blob',
        headers: { 'Authorization': `Bearer ${accessToken}` }
    } as AxiosRequestConfig;
    const response = await userClient.request<Blob | null>(config);
    if (response.data == null) {
        return Promise.reject();
    }
    else {
        // return mediainfo
        const promise = new Promise<MediaInfo | null>((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result as string | null == null ? null : {
                    type: MediaInfoType.Image,
                    // objectId: string,
                    url: reader.result,
                } as MediaInfo
            );
            reader.onerror = reject;
            reader.readAsDataURL(response.data!);
        });
        try{
            return await promise;
        }
        catch {
            return null;
        }
    }
};

export async function SetAvatar(accessToken : string | null | undefined, file: File, client?: AxiosInstance) {
    try {
        const formData = new FormData();
        formData.append('file', file);
        const axiosConfig = {
            headers:{
                // Accept: 'text/plain',
                ContentType: 'multipart/form-data',
                Authorization: `Bearer ${accessToken}`
            },
        }
        client ??= userClient;      
        await client.post(`SetAvatar`, formData, axiosConfig);
    }
    catch (error)
    {
        CatchError(error);
    }
}

export async function DeleteAvatar(accessToken : string | null | undefined, client?: AxiosInstance | null) {

    try {
        const axiosConfig = {
            headers:{
                Accept: 'text/plain',
                ContentType: 'application/json',
                Authorization: `Bearer ${accessToken}`
            }
        }
        client ??= userClient;
        // const { data } = await client.post(`DeleteAvatar`, model, axiosConfig);
        await client.post(`DeleteAvatar`, axiosConfig);

        // console.log(JSON.stringify(data, null, 4));

        // 👇️ "response status is: 200"
        // console.log('response status is: ', status);

        // return data;
    }
    catch (error)
    {
        CatchError(error);
    }
}

export async function SetUserInformation(accessToken : string | null | undefined, model: UserInformationEditModel, client?: AxiosInstance | null) {
    try {
        const axiosConfig = {
            headers:{
                Accept: 'text/plain',
                ContentType: 'application/json',
                Authorization: `Bearer ${accessToken}`
            }
        }
        client ??= userClient;
        await client.post(`SetUserInformation`, model, axiosConfig);
    }
    catch (error)
    {
        CatchError(error);
    }
}

export async function SetBirthDate(accessToken : string | null | undefined, model: BirthDateEditModel, client?: AxiosInstance | null) {
    try {
        const axiosConfig = {
            headers:{
                Accept: 'text/plain',
                ContentType: 'application/json',
                Authorization: `Bearer ${accessToken}`
            }
        }

        console.log('model');
        console.log(model);

        client ??= userClient;
        await client.post(`SetBirthDate`, model, axiosConfig);
    }
    catch (error)
    {
        CatchError(error);
    }
}

export async function SetLanguage(accessToken : string | null | undefined, model: LanguageEditModel, client?: AxiosInstance | null) {
    try {
        const axiosConfig = {
            headers:{
                Accept: 'text/plain',
                ContentType: 'application/json',
                Authorization: `Bearer ${accessToken}`
            }
        }
        client ??= userClient;
        await client.post(`SetLanguage`, model, axiosConfig);
    }
    catch (error)
    {
        CatchError(error);
    }
}

/* SESSIONS */
export async function GetSessions(accessToken : string | null | undefined, client?: AxiosInstance | null) : Promise<Array<SessionModel> | undefined> {

    try {
        const axiosConfig = {
            headers:{
                // Accept: 'text/plain',
                // ContentType: 'application/json',
                Authorization: `Bearer ${accessToken}`
            }
        }
        client ??= accountClient;
        // const { data } = await client.post(`DeleteAvatar`, model, axiosConfig);
        const { data } = await client.get<Array<SessionModel>>(`Sessions`, axiosConfig);

        // console.log(JSON.stringify(data, null, 4));

        // 👇️ "response status is: 200"
        // console.log('response status is: ', status);

        return data;
    }
    catch (error)
    {
        CatchError(error);
    }
}

export async function DeleteSession(accessToken : string | null | undefined, model: DeleteSessionModel, client?: AxiosInstance | null) {

    try {
        const axiosConfig = {
            headers:{
                Accept: 'text/plain',
                ContentType: 'application/json',
                Authorization: `Bearer ${accessToken}`
            }
        }
        client ??= accountClient;
        // const { data } = await client.post(`DeleteAvatar`, model, axiosConfig);
        await client.post(`Sessions/Delete`, model, axiosConfig);

        // console.log(JSON.stringify(data, null, 4));

        // 👇️ "response status is: 200"
        // console.log('response status is: ', status);

        // return data;
    }
    catch (error)
    {
        CatchError(error);
    }
}

export async function DeleteCurrentSession(accessToken : string | null | undefined, client?: AxiosInstance | null) {

    try {
        const axiosConfig = {
            headers:{
                Accept: 'text/plain',
                ContentType: 'application/json',
                Authorization: `Bearer ${accessToken}`
            }
        }
        client ??= accountClient;
        await client.post(`Sessions/DeleteCurrent`, axiosConfig);
    }
    catch (error)
    {
        CatchError(error);
    }
}

export async function DeleteAllSessions(accessToken : string | null | undefined, client?: AxiosInstance | null) {

    try {
        const axiosConfig = {
            headers:{
                Accept: 'text/plain',
                ContentType: 'application/json',
                Authorization: `Bearer ${accessToken}`
            }
        }
        client ??= accountClient;
        await client.post(`Sessions/DeleteAll`, axiosConfig);
    }
    catch (error)
    {
        CatchError(error);
    }
}