/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
import './style.css'

function getRichText(weex) {
    const {
        extractComponentStyle
    } = weex

    return {
        name: 'weex-richtext',
        computed: {
            wrapperClass() {
                const classArray = ['weex-richtext', 'weex-richtext-wrapper', 'weex-ct']
                return classArray.join(' ')
            }
        },

        methods: {
            //141953:richtext
            onClick(e) {
                var attrs = e.target.attributes;
                var value = '';
                for(var key in attrs) {
                    if (attrs[key].name == 'pseudo-ref' && attrs[key].nodeValue) {
                    value = attrs[key].nodeValue;
                    }
                }
                if(value!=='') {
                    this.$emit('itemclick', {pseudoRef: value})
                }
            },
            createChildren(h) {
                const slots = this.$slots.default || []
                //只支持三种子元素：image,span,a
                this._children = slots.filter(vnode => {
                    if (!vnode.tag && vnode.tag != 'figure' && vnode.tag != 'span' && vnode.tag != 'a' && !vnode.componentOptions) return false
                    return true
                })
                return [
                    h('div', {
                        ref: 'inner',
                        staticClass: 'weex-richtext-inner weex-ct',
                        on: {
                            click: this.onClick
                        }
                    }, this._children)
                ]
            }
        },

        render(createElement) {
            this.weexType = 'richtext'

            return createElement('div', {
                ref: 'wrapper',
                attrs: { 'weex-type': 'richtext' },
                staticClass: this.wrapperClass,
                staticStyle: extractComponentStyle(this)
            }, this.createChildren(createElement))
        }
    }
}

export default {
    init(weex) {
        weex.registerComponent('richtext', getRichText(weex))
    }
}
