package com.sw.mes.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PriorityQueue {

    private int maxSize;
    private Object[] priQueArray;
    private int nItems;

    public PriorityQueue(int s){
        maxSize = s;
        priQueArray = new Object[maxSize];
        nItems = 0;
    }

    //插入数据
    public void insert(Object value){
        if (value == null) {
            return;
        }
        int j;
        if(nItems == 0){
            priQueArray[nItems++] = value;
        }else{
            j = nItems -1;
            //选择的排序方法是插入排序，按照从小到大的顺序排列，越大的越在队列的顶端
            while(j >=0 && compare(value, priQueArray[j]) < 0 ){
                priQueArray[j+1] = priQueArray[j];
                j--;
            }
            priQueArray[j+1] = value;
            nItems++;
        }
    }

    public int compare(Object obj1, Object obj2) {
        String o1 = obj1.toString();
        String o2 = obj2.toString();
        if (isNumeric(o1) && isNumeric(o2)) {
            double od1 = Double.valueOf(o1);
            double od2 = Double.valueOf(o2);
            if (od1 >= od2) {
                return 1;
            } else {
                return -1;
            }
        }
        return o1.compareTo(o2);
    }

    public boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]+.*[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }

    //移除数据,由于是按照小da排序的，所以移除数据我们指针向下移动
    public Object remove(){
        int k = nItems -1;
        Object value = priQueArray[k];
        priQueArray[k] = null;//-1表示这个位置的数据被移除了
        nItems--;
        return value;
    }

    //查看优先级最高的元素
    public Object peekMax(){
        return priQueArray[nItems-1];
    }

    //判断是否为空
    public boolean isEmpty(){
        return (nItems == 0);
    }

    //判断是否满了
    public boolean isFull(){
        return (nItems == maxSize);
    }

    public int getIndex(Object obj) {
        if(nItems > 0) {
            int k = nItems;
            while (k > 0) {
                if(priQueArray[--k].equals(obj)) {
                    return k;
                }
            }
        }
        return -1;
    }

}
