package com.epson.memcardacc;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.os.AsyncTask;

import java.util.ArrayList;

public class FileConvertViewModel extends AndroidViewModel {
    private final FileConvertTask.ConvertEndListener mConvertEndListener = new FileConvertTask.ConvertEndListener() {
        public void onConvertEnd(@NonNull FileConvertTask.ErrorType errorType, @Nullable ArrayList<String> arrayList) {
            FileConvertViewModel.mFileConvertStatusLiveData.setValue(new FileConvertStatus(ConvertStatus.TASK_END, errorType, arrayList));
        }
    };
    private final MutableLiveData<FileConvertStatus> mFileConvertStatusLiveData = new MutableLiveData<>();
    private FileConvertTask mFileConvertTask;

    enum ConvertStatus {
        TASK_NOT_STARTED,
        TASK_RUNNING,
        TASK_END
    }

    public static class FileConvertStatus {
        private final ArrayList<String> mConvertFileList;
        private final ConvertStatus mConvertStatus;
        private final FileConvertTask.ErrorType mErrorType;

        public FileConvertStatus() {
            this(ConvertStatus.TASK_NOT_STARTED);
        }

        public FileConvertStatus(ConvertStatus convertStatus) {
            this(convertStatus, FileConvertTask.ErrorType.NO_ERROR, (ArrayList<String>) null);
        }

        public FileConvertStatus(ConvertStatus convertStatus, FileConvertTask.ErrorType errorType, ArrayList<String> arrayList) {
            mErrorType = errorType;
            mConvertStatus = convertStatus;
            mConvertFileList = arrayList;
        }

        @NonNull
        public ConvertStatus getConvertStatus() {
            return mConvertStatus;
        }

        @NonNull
        public FileConvertTask.ErrorType getErrorType() {
            return mErrorType;
        }

        @Nullable
        public ArrayList<String> getConvertFileList() {
            return mConvertFileList;
        }
    }

    public FileConvertViewModel(@NonNull Application application) {
        super(application);
        mFileConvertStatusLiveData.setValue(new FileConvertStatus());
    }

    public void startConvert(@NonNull ArrayList<String> arrayList) {
        mFileConvertStatusLiveData.setValue(new FileConvertStatus(ConvertStatus.TASK_RUNNING));
        mFileConvertTask = new FileConvertTask(arrayList, mConvertEndListener);
        mFileConvertTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Void[0]);
    }

    public LiveData<FileConvertStatus> getData() {
        return mFileConvertStatusLiveData;
    }
}
