package de.sebse.fuplanner.services.canteen.types;

import android.content.Context;
import androidx.annotation.NonNull;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Iterator;

public class Canteens implements Serializable, Iterable<Canteen> {
    public static final int[] availableCanteens = {27, 42, 813, 810, 811, 812, 821};
    private static final String FILE_NAME = "CanteensSaving";
    private SortedListCanteen list = new SortedListCanteen();

    public Canteen getCanteen(int id) {
        return this.list.getById(id);
    }

    public void addCanteen(int id, String name, String city, String address, double lat, double lng) {
        Canteen canteen = new Canteen(id, name, city, address, lat, lng);
        addCanteen(canteen);
    }

    private void addCanteen(Canteen canteen) {
        if (this.list.contains(canteen)) return;
        this.list.add(canteen);
    }

    public int size() {
        return this.list.size();
    }

    public Canteen get(int index) {
        return this.list.get(index);
    }

    public void update(Canteens canteens) {
        SortedListCanteen oldList = this.list;
        this.list = canteens.list;
        for (Canteen oldCanteen: oldList) {
            Canteen newCanteen = getCanteen(oldCanteen.getId());
            if (newCanteen != null) {
                for (Day day: oldCanteen) {
                    newCanteen.addDay(day);
                }
            }
        }
    }

    @NonNull
    @Override
    public Iterator<Canteen> iterator() {
        return new Iterator<Canteen>() {
            int i = 0;
            @Override
            public boolean hasNext() {
                return i < size();
            }

            @Override
            public Canteen next() {
                return get(i++);
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("You are not allowed to remove an entry!");
            }
        };
    }

    public static Canteens load(Context context) throws IOException, ClassNotFoundException {
        FileInputStream fis = context.openFileInput(FILE_NAME);
        ObjectInputStream is = new ObjectInputStream(fis);
        Canteens modules = (Canteens) is.readObject();
        is.close();
        fis.close();
        return modules;
    }

    public void save(Context context) throws IOException {
        FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(this);
        os.close();
        fos.close();
    }

    public void delete(Context context) {
        context.deleteFile(FILE_NAME);
    }

    @NonNull
    @Override
    public String toString() {
        return this.list.toString();
    }
}
