package com.bytesw.bytebot.controller;

import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AppSettingsController {

    @Value("${application.logo.type:png}")
    private String type;

    @Value("classpath:logo.txt")
    Resource resourceFile;

    @Value("${application.show-side-bar:true}")
    private boolean showSideBar;

    @Autowired
    private GsonBuilder gsonBuilder;

    @GetMapping("/settings/information")
    public ResponseEntity<String> getAppSettings() {
        HttpStatus hs = HttpStatus.OK;
        Map<String, Object> appSettings = new HashMap<>();
        appSettings.put("tipo", type);
        appSettings.put("logoBase64", getDefaultLogo());
        //you
        // appSettings.put("showSideBar", true);
        return new ResponseEntity<>(gsonBuilder.disableHtmlEscaping().create().toJson(appSettings), hs);
    }

    public String getDefaultLogo() {
        String str = "";
        StringBuffer buf = new StringBuffer();
        InputStream is = null;
        try {
            is = resourceFile.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            if (is != null) {
                while ((str = reader.readLine()) != null) {
                    buf.append(str + "" );
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try { is.close(); } catch (Throwable ignore) {}
        }
        return buf.toString();
    }
}
