package yi.iu.processor.filter;

import java.awt.*;
import yi.iu.processor.ImageProcessor;

/**
 * Class Masker masks on the given image using the given mask.  The pixels on
 * the boundary will be leaved alone and it is not nessary to normalized the
 * total of the mask (Masker will do it anyway)
 *
 * The default mask is 3*3.
 *
 * If you want to process the image with the mask:
 *
 * 1 3 1
 * 3 5 3
 * 1 3 1
 *
 * follow this example:
 *
 * int[] mask = new int[] {1, 3, 1, 3, 5, 3, 1, 3, 1};
 * Masker masker = new Masker(mask, 3, 3};
 * int[] rst = masker.getProcessed(image, d);
 *
 */

public class Masker extends ImageProcessor
{
    int[] mask;
    int mwidth, mheight;
    public Masker()
    {
        mwidth=mheight=3;
        mask= new int[mwidth*mheight];
        for (int i=0;i<mask.length;i++)
            mask[i]=1;
    }

    public Masker(int[] m, int w, int h)
    {
        mwidth=w;
        mheight=h;
        mask= m;
    }

    public int[] getProcessedPseudoColor(int source[], Dimension d)
    {
        // This method is derived from class ImageProcessor
        // to do: code goes here
        return null;
    }

    public int[] getProcessed(int source[], Dimension d)
    {
        int w=d.width, h=d.height;
        int[] rst= new int[w*h];
        int[] ptr= new int[mask.length];
        int total=0;
        int gw= mwidth/2, gh= mheight/2;    // gap along the image
        for (int i=0;i<mheight;i++) {
            for (int j=0;j<mwidth;j++) {
                ptr[i*mwidth+j]=(i-gh)*w+j-gw;
                total+= mask[i*mwidth+j];
            }
        }
        for (int i=gh,hptr=gh*w; i<h-gh; i++,hptr+=w) {
            for (int j=gw,eptr=hptr+gw; j<w-gw; j++,eptr++) {
                for (int k=0;k<mask.length;k++) {
                    rst[eptr]+= source[eptr+ptr[k]]*mask[k];
                }
                if (total>1) rst[eptr]/=total;
            }
        }
        return rst;
    }

    int[] ptr= null;
    int width;
    int total=0;
    int gw, gh;    // gap along the image
    public int getProcessed(int source[], Dimension d, int x, int y) {
      int w=d.width, h=d.height;
      if (ptr == null || width != w) {
        System.err.println("recalculate the eptr");
        ptr= new int[mask.length];
        total = 0;
        width = w;
        gw= mwidth/2; gh= mheight/2;    // gap along the image
        for (int i=0;i<mheight;i++) {
            for (int j=0;j<mwidth;j++) {
                ptr[i*mwidth+j]=(i-gh)*w+j-gw;
                total+= mask[i*mwidth+j];
            }
        }
      }
      int rst = 0;
      int eptr = y*w+x;
      if (y>=gh&&y<h-gh&&x>=gw&&x<w-gw) {
        for (int k=0;k<mask.length;k++) {
          rst+= source[eptr+ptr[k]]*mask[k];
        }
      }
//      if (total>1) rst/=total;
      return rst;
    }
}