import Device.NanoPi;

import java.util.Timer;
import java.util.TimerTask;
import Audio.*;
import org.pmw.tinylog.Logger;


public class Main {
    static int btnBuffVal;
    static AudioPlayer AP = new AudioPlayer();

    public static void main(String[] args) {
        var npi = new NanoPi();
        int Freq = 44100;


        DigitalInput talkButton = new DigitalInput(npi.GetGPIO(12));
        DigitalOutput LED1 = new DigitalOutput(npi.GetGPIO(20),false);
        int devIndx = AP.FindOutputDevice("USB");
        if (devIndx != -1){
            if (AP.OpenDevice(devIndx,Freq)){
                AP.setMasterVolume(50);
            }
        }else Logger.error("Failed to find USB Device");

        if (AP.isInited()) {
            System.out.println("Main Timer is started!");
            Timer MainTimer = new Timer();
            MainTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println(btnBuffVal);
                    if(talkButton.ReadState() == 1 ){
                        //button is release
                        if (btnBuffVal > 2){
                            //button is pressed
                            ButtonIsShortPressed();
                        }
                        btnBuffVal = 0;
                    }else{
                        //button is pressed
                        btnBuffVal = btnBuffVal + 1;

                    }
                }
            },0,500);
        }else{
            System.out.println("Stop Program!");
        }

    }

    static PlaybackEvent pe = new PlaybackEvent() {
        @Override
        public void onPlaybackStart(AudioFileProperties prop) {
            Logger.info("Playback Started{}", prop.filename);
        }

        @Override
        public void onPlaybackFinished(AudioFileProperties prop) {
            Logger.info("Playback Finished{}", prop.filename);
        }

        @Override
        public void onPlaybackFailure(AudioFileProperties prop, String reason) {
            Logger.info("Playback Failed{} Reason: {}", prop.filename, reason);
        }

        @Override
        public void onPlaybackLooped(AudioFileProperties prop) {
            Logger.info("Playback Looped{}", prop.filename);
        }
    };

    private static void ButtonIsShortPressed(){
        //play file here
        System.out.println("Button is pressed");
        playFile("/home/pi/test.wav");
    }

    private static void playFile(String filename){
        AudioFileProperties prop = AP.OpenAudioFile(filename);
        if (prop!=null){
            AP.PlayAudioFile(prop, false, pe);
        }
    }

}