package ru.bitel.bgbilling.modules.tv.dyn.tvip;

import java.io.OutputStreamWriter;
import java.io.Writer;

import org.json.JSONArray;
import org.json.JSONObject;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import ru.bitel.bgbilling.kernel.base.server.logger.BGLogger;
import ru.bitel.bgbilling.modules.tv.server.bean.enums.ModuleSetupKeys;
import ru.bitel.bgbilling.modules.tv.server.handler.HttpHandler;
import ru.bitel.bgbilling.server.util.Setup;

/**
 * https://docs.tvip.ru/ru/tms/usage/billing_api.html#billing-api
 */
public class TVIPBillingApiHandler
    extends BGLogger
    implements HttpHandler
{
    @Override
    public void handle( int moduleId, HttpServletRequest request, HttpServletResponse response )
    {
        String[] paths = getPath( request );
        if ( paths.length > 5 && "api".equals( paths[4] ) )
        {
            switch ( paths[5] )
            {
                case "cabinet":
                {
                    if ( paths.length == 6 )
                    {
                        apiCabinet( moduleId, request, response );
                    }
                    else if ( paths.length > 6 && "password".equals( paths[6] ) )
                    {
                        apiCabinetPassword( moduleId, request, response );
                    }
                    break;
                }
                case "tariff": apiTariffId( paths.length > 6 ? paths[6] : null,  moduleId, request, response ); break;
                case "subscribe": apiCabinet( moduleId, request, response ); break;
                case "unsubscribe": apiTariffId( paths.length > 6 ? paths[6] : null,  moduleId, request, response ); break;
                default: 
            }
        }
        HttpHandler.super.handle( moduleId, request, response );
    }
    
    /**
     * GET /api/cabinet - личный кабинет пользователя
     * @param moduleId
     * @param request
     * @param response
     */
    protected void apiCabinet( int moduleId, HttpServletRequest request, HttpServletResponse response )
    {
        JSONObject result = new JSONObject()
            .put( "contacts", contacts( moduleId ) )
            .put( "account", account( moduleId, request ) )
            .put( "services", services( moduleId, request ) );
        
        sendData( response, result.toString() );
    }

    /**
     * POST /api/cabinet/password - смена пароля Аккаунта
     * @param moduleId
     * @param request
     * @param response
     */
    protected void apiCabinetPassword( int moduleId, HttpServletRequest request, HttpServletResponse response )
    {
    }
    
    /**
     * GET /api/tariff/{id} - детальное описание тарифа 
     * @param id
     * @param moduleId
     * @param request
     * @param response
     */
    protected void apiTariffId( String id, int moduleId, HttpServletRequest request, HttpServletResponse response )
    {
    }
    
    /**
     * POST /api/switch - смена тарифного плана 
     * @param moduleId
     * @param request
     * @param response
     */
    protected void apiSwitch( int moduleId, HttpServletRequest request, HttpServletResponse response )
    {
    }
    
    /**
     * POST /api/subscribe - подписка на новый тарифный план 
     * @param moduleId
     * @param request
     * @param response
     */
    protected void apiSubscribe( int moduleId, HttpServletRequest request, HttpServletResponse response )
    {
    }
    
    /**
     * POST /api/unsubscribe - отказ от подписки 
     * @param moduleId
     * @param request
     * @param response
     */
    protected void apiUnsubscribe( int moduleId, HttpServletRequest request, HttpServletResponse response )
    {
    }
    
    protected String contacts( int moduleId )
    {
        return Setup.getSetup().getModuleSetup( moduleId ).get( ModuleSetupKeys.TVIP_CONTACTS );
    }
    
    protected JSONObject account( int moduleId, HttpServletRequest request )
    {
        int accountId = 1;
        String fullname = "Имя А.";
        String balance = "10 $";
        boolean enabled = true;
        String credentials = "132379-2014-01-01";
        
        return new JSONObject()
            .put( "id", accountId )
            .put( "fullname", fullname )
            .put( "balance", balance )
            .put( "enabled", enabled )
            .put( "account_credentials", credentials );
    }

    protected JSONArray services( int moduleId, HttpServletRequest request )
    {
        return new JSONArray();
    }
    
    private void sendData( HttpServletResponse response, String data )
    {
        response.setStatus( HttpServletResponse.SC_OK );
        response.setContentType( "application/json; charset=utf-8" );
        try ( Writer writer = new OutputStreamWriter( response.getOutputStream(), "UTF-8" ) )
        {
            writer.write( data );
            writer.flush();
        }
        catch( Exception ex )
        {
            logError( ex );
        }
    }

    private void sendError( HttpServletResponse response, String message )
    {
        response.setStatus( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
        response.setContentType( "application/json; charset=utf-8" );
        try ( Writer writer = new OutputStreamWriter( response.getOutputStream(), "UTF-8" ) )
        {
            JSONObject json = new JSONObject()
                .put( "code", 500 )
                .put( "message", message );
            
            writer.write( json.toString() );
            writer.flush();
        }
        catch( Exception ex )
        {
            logError( ex );
        }
    }
}