import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs } from '@wordpress/url';
import { ServiceErrorHandler } from './ServiceErrorHandler';
import { AppConfig } from '../config/AppConfig';
import appDebug from "../utils/appDebug";

const DEBUG_CATEGORY = "MenuItemService";

export const MenuItemService = {

  fetchTopLevelItems: async(menuID, lastItemID = null) => {

    let endpointUrl = `${AppConfig.endpointBaseUrl}/menu/${menuID}/items`;

    if (lastItemID && !isNaN(lastItemID)) {
      endpointUrl += "/" + lastItemID.toString();
    }

    if (menuID) {
      return apiFetch( { path: endpointUrl } ).then( 
        ( result ) => {
          appDebug(DEBUG_CATEGORY, 'returned top level menu items', result?.items);

          ServiceErrorHandler.assertSuccess(result);

          return result;
        
        }
      ).catch( 
        (error) => {
          console.warn(error);
          return error;
        }
      );
    }
    
    return Promise.resolve(null);
  
  },
  fetchChildItems: async (menuID, itemID, lastItemID = null) => {
    
    appDebug(DEBUG_CATEGORY, 'fetching menu subitems',menuID, itemID, lastItemID);
    
    let endpointUrl = `${AppConfig.endpointBaseUrl}/menu/${menuID}/item/${itemID}/children`;

    if (lastItemID) {
      endpointUrl += '/' + lastItemID.toString();
    }

    if (menuID) {
      const result = await apiFetch( 
        { 
          path: endpointUrl
        } 
      ).catch((err) => {
        ServiceErrorHandler.handleError(err, { debug_category: DEBUG_CATEGORY });
      });

      ServiceErrorHandler.assertSuccess(result);

      return result;
    }

    return Promise.resolve(null);
  
  },
  saveItemRevision: async (menuID, revisionID, lastItemID = null) =>  {

    if (!menuID) {
      throw new Error("Missing MenuID in SaveItemRevision");
    }
    
    const result = await apiFetch( 
      { 
        path: `${AppConfig.endpointBaseUrl}/menu/update`,
        method: 'POST', 
        data: { 
          'menu_id': menuID,
          'revision_id': revisionID,
          'last_item_id': lastItemID
        }
      } 
    ).catch((err) => {
      ServiceErrorHandler.handleError(err, { debug_category: DEBUG_CATEGORY });
    });

    ServiceErrorHandler.assertSuccess(result);

    return result;

  },
  processDeletions: async (menuID, revisionID) =>  {

    if (!menuID) {
      throw new Error("Missing MenuID in processDeletions");
    }

    if (!revisionID) {
      throw new Error("Missing revisionID in processDeletions");
    }
    
    const result = await apiFetch( 
      { 
        path: `${AppConfig.endpointBaseUrl}/menu/process-deletions`,
        method: 'POST', 
        data: { 
          'menu_id': menuID,
          'revision_id': revisionID
        }
      } 
    ).catch((err) => {
      ServiceErrorHandler.handleError(err, { debug_category: DEBUG_CATEGORY });
    });

    ServiceErrorHandler.assertSuccess(result);

    return result;

  },  
  saveItems: async (menuID, menuItems) =>  {

    if (!menuID) {
      throw new Error("Missing MenuID in SaveItems");
    }
    
    const result = await apiFetch( 
      { 
        path: `${AppConfig.endpointBaseUrl}/menu/update`,
        method: 'POST', 
        data: { 
          'items': menuItems,
          'menu_id': menuID
        }
      } 
    ).catch((err) => {
      ServiceErrorHandler.handleError(err, { debug_category: DEBUG_CATEGORY });
    });

    ServiceErrorHandler.assertSuccess(result);

    return result;

  },
  prepareRevisionForSave: async (menuID, menuItems) =>  {

    if (!menuID) {
      throw new Error("Missing MenuID in SaveItems");
    }
    
    const result = await apiFetch( 
      { 
        path: `${AppConfig.endpointBaseUrl}/menu/prepare-revision`,
        method: 'POST', 
        data: { 
          'items': menuItems,
          'menu_id': menuID
        }
      } 
    ).catch((err) => {
      ServiceErrorHandler.handleError(err, { debug_category: DEBUG_CATEGORY });
    });

    ServiceErrorHandler.assertSuccess(result);

    return result;

  },
  postSaveActions: async (menuID) =>  {

    const result = await apiFetch( 
      { 
        path: `${AppConfig.endpointBaseUrl}/menu/${menuID}/post-save-actions`,
        method: 'GET'
      } 
    ).catch((err) => {
      ServiceErrorHandler.handleError(err, { debug_category: DEBUG_CATEGORY });
    });

    ServiceErrorHandler.assertSuccess(result);

    return result;

  },
  refreshItems: async(menuID, menuItems, overrideFields = []) => {

    if (!menuID) {
      throw new Error("Missing menuID in refreshItems");
    }

    appDebug(DEBUG_CATEGORY, 'refreshed menu items', menuItems);

    const result = await apiFetch( 
      { 
        path: `${AppConfig.endpointBaseUrl}/menu/${menuID}/items/refresh`,
        method: 'POST', 
        data: { 'items': menuItems,
                'override_fields': overrideFields 
              } 
      } 
    ).catch((err) => {
      ServiceErrorHandler.handleError(err, { debug_category: DEBUG_CATEGORY });
    });

    ServiceErrorHandler.assertSuccess(result, {assertFieldValues: ['items']});

    return result.items;    
  }

}
