package com.xixun.xixunplayer;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Path;
import android.view.Choreographer;
import android.view.View;

import androidx.annotation.NonNull;

@SuppressLint("ViewConstructor")
public class SrcBorder extends View implements Choreographer.FrameCallback {
    Bitmap img;
    int[] lens = new int[4];
    Path[] paths = new Path[4];
    int[] offs = new int[]{0,0,0,0};
    byte eff;
    int interval;

    public SrcBorder(Prog prog, String path, String effStr, int speed) {
        super(prog.getContext());
        img = BitmapFactory.decodeFile(path);
        if(effStr.startsWith("ro")) eff = 'r';
        else if(effStr.startsWith("bl")) eff = 'b';
        if(eff=='r') interval = speed==1 ? 4 : (speed==2 ? 2 : 1);
        else interval = speed==1 ? 30 : (speed==2 ? 15 : 4);
        if(eff!=0) prog.calls.add(this);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        lens[0] = lens[2] = w;
        lens[1] = lens[3] = h;
        int bdWidth = img.getHeight();
        for(int i=0; i<2; i++) {
            Path path = new Path();
            path.moveTo(0,0);
            path.lineTo(lens[i], 0);
            path.lineTo(lens[i] - bdWidth, bdWidth);
            path.lineTo(bdWidth, bdWidth);
            path.close();
            paths[i] = paths[i+2] = path;
        }
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);
        if(eff!='b' || offs[0] <= 0) {
            int bdWidth = img.getHeight();
            int bdLen = img.getWidth();
            offs[1] = (offs[0] + lens[0]-bdWidth)%bdLen;
            offs[2] = (offs[0] + lens[0]+lens[1]-bdWidth*2)%bdLen;
            offs[3] = (offs[0] + lens[0]*2+lens[1]-bdWidth*3)%bdLen;
            for(int ll=0; ll<4; ll++) {
                canvas.save();
                canvas.clipPath(paths[ll]);
                for(int x=-offs[ll]; x<lens[ll]; x+=bdLen) canvas.drawBitmap(img, x, 0, null);
                canvas.restore();
                if(ll<3) {
                    canvas.translate(lens[ll], 0);
                    canvas.rotate(90);
                }
            }
        }
    }

    int freshCnt;

    @Override
    public void doFrame(long ms) {
        if(! isShown()) {
            freshCnt = offs[0] = 0;
            return;
        }
        if(freshCnt < interval) freshCnt++;
        else {
            freshCnt = 1;
            if(eff=='r') {
                if(offs[0] <= 0) offs[0] = img.getWidth()-1;
                else offs[0]--;
            } else offs[0] = offs[0]==0 ? 1 : 0;
            invalidate();
        }
    }
}