import { Topping, ChangeToppingDto, } from "../generated/graphql";
import { ToppingList } from "../data/topping-list";
import { v4 as uuidv4 } from 'uuid';
import { EEXIST } from "constants";
import { PubSub } from "apollo-server";


export class ToppingResolver {

    static toppingEvent = new PubSub();
    static events = {
        TOPPING_CHANGED: "toppingChanged",
    }

    static getById = (id: string): Topping => {
        return ToppingList.filter(topping => topping.id === id)[0];
    };

    static getByName = (name: string): Topping => {
        return ToppingList.filter(topping => topping.name === name)[0];
    };

    static list = (): Topping[] => {
        return ToppingList;
    };

    static delete = (id: string): Topping => {
        const index = ToppingList.indexOf(ToppingResolver.getById(id));
        if ( index ) {
            ToppingList.splice(index, 1)
        }
        return ToppingResolver.getById(id)
    };

    static create = (toppingCreateDto: ChangeToppingDto): Topping => {
        const topping: Topping = {
            id: uuidv4(),
            name: toppingCreateDto.name,
        }
        ToppingList.push(topping);
        console.log(`Create Topping ...`, topping);
        ToppingResolver.toppingEvent.publish(ToppingResolver.events.TOPPING_CHANGED, {
            toppingsChanged: ToppingList
        });
        return topping;
    };


    static update = (toppingId: string, toppingUpdateDto: ChangeToppingDto): Topping => {
        const topping = ToppingResolver.getById(toppingId);
        if (!topping) {
            throw new Error(
                `No Topping found with id ${toppingId}`
            )
        }
        topping.name = toppingUpdateDto.name;
        const toppingIndex = ToppingList.indexOf(topping);
        ToppingList[toppingIndex] = topping;
        ToppingResolver.toppingEvent.publish(ToppingResolver.events.TOPPING_CHANGED, {
            toppingsChanged: ToppingList
        });
        console.log(`Update Topping ...`, topping)
        return topping;
    };

}